package dk.dtu.android.transport;

import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.DialogError;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.android.Facebook.DialogListener;

import dk.dtu.android.facebook.FacebookConnect;
import dk.dtu.android.facebook.BaseRequestListener;
import dk.dtu.android.transport.db.KeyValueTable;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class FacebookLogin extends Activity {
	
	public final static int REQUEST_ID = 88;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.facebook_login);
        
        final FacebookConnect fc = FacebookConnect.getInstance();
        fc.facebook.authorize(this, new String[] {"email"}, new DialogListener() {
            public void onComplete(Bundle values) {
            	fc.asyncRunner.request("me", new MeRequestListener());
            }

            public void onFacebookError(FacebookError error) {}

            public void onError(DialogError e) {}

            public void onCancel() {}
        });
    }
    
    public class MeRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                Log.d("Transport", "Facebook response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                final String name = json.getString("name");
                String email = json.getString("email");
                String fuserId = json.getString("id");
                String link = json.getString("link");
                if (TransportAPI.facebookInformation(fuserId, name, email, link))
        		{
        			KeyValueTable.setValue(Constants.USER_ID, TransportAPI.userId);
        			setResult(RESULT_OK);
        		}
                else {
                	setResult(Activity.RESULT_CANCELED);
        		}

            } catch (JSONException e) {
                Log.w("Transport", "JSON Error in response");
                setResult(Activity.RESULT_CANCELED);
            } catch (FacebookError e) {
                Log.w("Transport", "Facebook Error: " + e.getMessage());
                setResult(Activity.RESULT_CANCELED);
            }
            finish();
        }
    }
    
    public static void loginIfRequired(Activity activity){
    	String userId = KeyValueTable.getValue(Constants.USER_ID);
    	if (userId == null)
    	{
            Intent myIntent = new Intent(activity, FacebookLogin.class);
            activity.startActivityForResult(myIntent, FacebookLogin.REQUEST_ID);
    	}
    	else
    	{
    		TransportAPI.userId = KeyValueTable.getValue(Constants.USER_ID); 
    	}
    }
}